package com.xyzwps.orm.jpa.repository;

import com.xyzwps.orm.model.User;
import com.xyzwps.orm.repository.UserRepository;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import java.util.Objects;
import java.util.Optional;

public class JpaUserRepository implements UserRepository {

    private final EntityManager em;

    public JpaUserRepository(EntityManager em) {
        this.em = Objects.requireNonNull(em);
    }


    @Override
    public int insert(User user) {
        em.persist(user);
        return user.getUserId();
    }

    @Override
    public void update(User user) {
        var $user = selectByUserId(user.getUserId());
        if ($user.isEmpty()) {
            throw new IllegalArgumentException("不可更新不存在的用户信息");
        }
        var pUser = $user.get();
        pUser.setUsername(user.getUsername());
        pUser.setVip(user.isVip());
        pUser.setVipDate(user.getVipDate());
        em.flush();
    }

    @Override
    public Optional<User> selectByUserId(int userId) {
        var jpql = "select u from User u where u.userId = :userId";
        try {
            var user = em.createQuery(jpql, User.class)
                    .setParameter("userId", userId)
                    .getSingleResult();
            return Optional.ofNullable(user);
        } catch (NoResultException ex) {
            return Optional.empty();
        }
    }
}
